package com.webserver.core;

Lianxipackage com.wedserver.core;

import com.webserver.http.HttpRequest;

import java.io.*;
import java.net.Socket;

/**
 * 处理与指定客户端的一次HTTP交互
 * 完成一次交互有三部分构成:
 * 1:解析请求
 * 2:处理请求
 * 3:响应客户端
 */
public class ClientHandler implements Runnable{
    private Socket socket;
    public ClientHandler (Socket socket){
        this.socket=socket;
    }
    public void run(){
        try {
            //1解析请求
            HttpRequest request=new HttpRequest(socket);


            //2处理请求

            //3发送响应
                        /*
                HTTP/1.1 200 OK(CRLF)
                Content-Type: text/html(CRLF)
                Content-Length: 2546(CRLF)(CRLF)
                1011101010101010101......
             */
            OutputStream out=socket.getOutputStream();
            String path=request.getUri();
            File file=new File("./webapps"+path);
            String str="HTTP/1.1 200 OK";
            byte[]arr=str.getBytes("ISO8859-1");
            out.write(arr);
            out.write(13);
            out.write(10);

            str="Content-Type: text/html";
            arr=str.getBytes("ISO8859-1");
            out.write(arr);
            out.write(13);
            out.write(10);

            str="Content-Length: "+file.length();
            arr=str.getBytes("ISO8859-1");
            out.write(arr);
            out.write(13);
            out.write(10);
            out.write(13);
            out.write(10);


            FileInputStream fin=new FileInputStream(file);
            arr=new byte[1024*10];
            int len;
            while ((len=fin.read(arr))!=-1){
                out.write(arr,0,len);
            }
            System.out.println("响应完毕");





            /*
            上述内容写好后,打开浏览器输入网址:http://localhost:8088:index.html
            测试读取浏览器发送过来的请求内容在控制台上确定内容
             */
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            //一次HTTP交互后要好于客户端断开连接(HTTP协议要求)
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }


}
